namespace ClassyBlog.Infrastructure
{
    using System.Collections.Concurrent;
    using System.Text.RegularExpressions;

    internal static class RegexExpressions
    {
        public static readonly Regex MetadataMarker =
            new Regex(@"^\s*$", MetadataMarkerOption);

        public static readonly Regex MacroMarker =
            new Regex(@"\{%(.[^%]+)%\}", MacroMarkerOption);

        private static readonly ConcurrentDictionary<string, Regex>
            SummaryExpressions = new ConcurrentDictionary<string, Regex>();

        private const RegexOptions MetadataMarkerOption =
            RegexOptions.Multiline |
            RegexOptions.CultureInvariant |
            RegexOptions.Compiled;

        private const RegexOptions MacroMarkerOption =
            RegexOptions.Singleline |
            RegexOptions.Multiline |
            RegexOptions.CultureInvariant |
            RegexOptions.Compiled;

        private const RegexOptions SummaryOption = RegexOptions.Singleline |
                                                   RegexOptions.Multiline |
                                                   RegexOptions.IgnoreCase |
                                                   RegexOptions.CultureInvariant |
                                                   RegexOptions.Compiled;

        public static Regex GetOrAddSummaryExpression(string tagName, int length)
        {
            var lowerCasedTagName = tagName.ToLower(Culture.Invariant);
            var key = lowerCasedTagName + ":" + length;

            var expression = SummaryExpressions.GetOrAdd(
                key,
                k => new Regex(
                    @"(.{" + length + @"}.*?<\/" + lowerCasedTagName + @">)",
                    SummaryOption));

            return expression;
        }
    }
}